package com.ruoyi.genpdf.controller;

import com.ruoyi.genpdf.service.LotteryPdfService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

@RestController
@RequestMapping("/api/pdf")
public class PdfController {

    @Autowired
    private LotteryPdfService lotteryPdfService;

    @GetMapping("/lottery-ticket")
    public ResponseEntity<Resource> generateLotteryTicket() throws IOException {
        Resource resource = lotteryPdfService.generateLotteryTicket();

        return ResponseEntity.ok()
                .contentType(MediaType.APPLICATION_PDF)
                .header(HttpHeaders.CONTENT_DISPOSITION,
                        "attachment; filename=\"lottery-ticket.pdf\"")
                .body(resource);
    }

    /**
     * 获取PDF文件流
     */
    @GetMapping("/getStreamPdf")
    public ResponseEntity<InputStreamResource> getPdfStream(@RequestParam String fileName) {
        try {

            String filePath = "D:/pdf_files/" + fileName + ".pdf";
            File file = new File(filePath);
            // 创建输入流
            FileInputStream fileInputStream = new FileInputStream(file);
            InputStreamResource resource = new InputStreamResource(fileInputStream);

            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Disposition", "inline; filename=" + fileName + ".pdf");
            headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
            headers.add("Pragma", "no-cache");
            headers.add("Expires", "0");

            return ResponseEntity.ok()
                    .headers(headers)
                    .contentLength(file.length())
                    .contentType(MediaType.APPLICATION_PDF)
                    .body(resource);

        } catch (FileNotFoundException e) {
            return ResponseEntity.notFound().build();
        }
    }
}
